package com.lizardmind.haofudoctor.ui.diagnosis.sickMan.advisory.kaifang.addChuFang

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup

import com.lizardmind.haofudoctor.R

import java.util.ArrayList

/**
 * Created by Administrator on 2016/11/24.
 * 标签viewgroup
 */
class DeleteTagsLayout(context: Context, attrs: AttributeSet) : ViewGroup(context, attrs) {
    private val listChild = ArrayList<View>()
    private var childHorizontalSpace: Int = 0//子布局横向间隔
    private var childVerticalSpace: Int = 0//子布局垂直间隔
    private var downX: Int = 0
    private var downY: Int = 0//按下的XY坐标

    internal var tagClickListener: TagClickListener? = null

    init {
        val attrArray = context.obtainStyledAttributes(attrs, R.styleable.TagsLayout)
        if (attrArray != null) {
            childHorizontalSpace = attrArray.getDimensionPixelSize(R.styleable.TagsLayout_tagHorizontalSpace, 0)
            childVerticalSpace = attrArray.getDimensionPixelSize(R.styleable.TagsLayout_tagVerticalSpace, 0)
            attrArray.recycle()
        }
    }

    /**
     * 负责设置子控件的测量模式和大小 根据所有子控件设置自己的宽和高
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        //        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 获得它的父容器为它设置的测量模式和大小
        val sizeWidth = View.MeasureSpec.getSize(widthMeasureSpec)
        var sizeHeight = View.MeasureSpec.getSize(heightMeasureSpec)
        val modeWidth = View.MeasureSpec.getMode(widthMeasureSpec)
        val modeHeight = View.MeasureSpec.getMode(heightMeasureSpec)
        // 如果是warp_content情况下，记录宽和高
        var width = 0
        var height = 0
        /**
         * 记录每一行的宽度，width不断取最大宽度
         */
        var lineWidth = 0
        /**
         * 每一行的高度，累加至height
         */
        var lineHeight = 0

        val count = childCount
        val left = paddingLeft
        val top = paddingTop

        //自己加的，将Child放入list，用于存储坐标tag，因为删除时需要使用坐标判断是删除哪个child
        listChild.clear()
        var view: View? = null
        if (count > 0) {
            view = getChildAt(0)
        }
        for (i in 0 until count) {
            listChild.add(view!!)
        }

        // 遍历每个子元素
        for (i in 0 until count) {
            val child = getChildAt(i)

            if (child.visibility == View.GONE)
                continue
            // 测量每一个child的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec)
            // 得到child的lp
            //            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            // 当前子空间实际占据的宽度
            //            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin + childHorizontalSpace;
            val childWidth = child.measuredWidth + childHorizontalSpace
            // 当前子空间实际占据的高度
            //            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin + childVerticalSpace;
            val childHeight = child.measuredHeight + childVerticalSpace
            /*
             * 如果加入当前child，则超出最大宽度，则的到目前最大宽度给width，类加height 然后开启新行
             */
            if (lineWidth + childWidth > sizeWidth - paddingLeft - paddingRight) {
                width = Math.max(lineWidth, childWidth)// 取最大的
                lineWidth = childWidth // 重新开启新行，开始记录
                // 叠加当前高度，
                height += lineHeight
                // 开启记录下一行的高度
                lineHeight = childHeight
                child.tag = Location(left, top + height, childWidth + left - childHorizontalSpace, height + child.measuredHeight + top)
            } else {// 否则累加值lineWidth,lineHeight取最大高度
                child.tag = Location(lineWidth + left, top + height, lineWidth + childWidth - childHorizontalSpace + left, height + child.measuredHeight + top)
                lineWidth += childWidth
                lineHeight = Math.max(lineHeight, childHeight)
            }

            //自己加的，存储child
            listChild[i] = child

        }
        width = Math.max(width, lineWidth) + paddingLeft + paddingRight
        height += lineHeight
        sizeHeight += paddingTop + paddingBottom
        height += paddingTop + paddingBottom
        setMeasuredDimension(if (modeWidth == View.MeasureSpec.EXACTLY) sizeWidth else width, if (modeHeight == View.MeasureSpec.EXACTLY) sizeHeight else height)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        val count = childCount
        for (i in 0 until count) {
            val child = getChildAt(i)
            if (child.visibility == View.GONE)
                continue
            val location = child.tag as Location
            child.layout(location.left, location.top, location.right, location.bottom)
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                downX = event.x.toInt()
                downY = event.y.toInt()
            }
            MotionEvent.ACTION_UP -> {
                val upX = event.x.toInt()
                val upY = event.y.toInt()
                if (tagClickListener != null && Math.abs(upX - downX) <= 3 && Math.abs(upY - downY) <= 3) {
                    for (i in listChild.indices) {
                        val location = listChild[i].tag as Location
                        if (upX >= location.left && upX <= location.right
                                && upY >= location.top && upY <= location.bottom) {
                            tagClickListener!!.tagClick(i)

                        }
                    }
                }
            }
        }
        return true
    }

    /**
     * 记录子控件的坐标
     */
    internal inner class Location(var left: Int, var top: Int, var right: Int, var bottom: Int)

    /**
     * tag点击事件
     */
    interface TagClickListener {
        fun tagClick(position: Int)
    }

    /**
     * 设置点击监听
     * @param tagClickListener
     */
    fun setTagClickListener(tagClickListener: TagClickListener) {
        this.tagClickListener = tagClickListener
    }
}
